package com;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by george on 2016/12/9.
 */
@Controller
@RequestMapping("/home")
public class HomeController {

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index() {
        return "home/index";
    }

    @RequestMapping(value = "code", method = RequestMethod.GET)
    public ModelAndView code(@RequestParam(value = "code", required = false) String code, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        result.addObject("result", "success");
        result.addObject("code", code);
        return result;
    }

    @RequestMapping(value = "access_token", method = RequestMethod.POST)
    public
    @ResponseBody
    String access_token(@RequestBody OauthData data) {
        String url = data.getToken_url();
        Map<String, String> param = new HashMap<String, String>();
        param.put("grant_type", "authorization_code");
        param.put("client_id", data.getClient_id());
        param.put("client_secret", data.getClient_secret());
        param.put("redirect_uri", data.getRedirect_uri());
        param.put("code", data.getCode());
        String response = null;
        try {
            response = HttpClient.sendGet(data.getToken_url(), param);
        } catch (Exception e) {
            e.printStackTrace();
            param.put("error", e.getMessage());
        }
        return response;
    }
}
